package com.gs.disk.modules.headImgAndWallper.service.mobile;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gs.entity.R;
import com.gs.common.exception.RenException;
import com.gs.disk.controller.common.OssController;
import com.gs.disk.entity.OssEntity;
import com.gs.disk.modules.headImgAndWallper.dao.mobile.MobileCategoryDao;
import com.gs.disk.modules.headImgAndWallper.dao.mobile.MobileResourceDao;
import com.gs.disk.modules.headImgAndWallper.dto.ResourceDto;
import com.gs.disk.modules.headImgAndWallper.entity.CategoryEntity;
import com.gs.disk.modules.headImgAndWallper.entity.ResourceEntity;
import com.gs.disk.service.common.OssService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class MobileResourceService extends ServiceImpl<MobileResourceDao, ResourceEntity> {

    @Resource
    private MobileResourceDao mobileResourceDao;

    @Resource
    private MobileCategoryDao mobileCategoryDao;

    @Resource
    private OssController ossController;

    @Resource
    private OssService ossService;


    /**
     * 根据分类名获取资源列表
     * @param categoryId 分类id
     * @return
     */
    public Map<String, List<ResourceDto>> list(Long categoryId, Long page, Long limit) {
        Map<String, List<ResourceDto>> listMap = mobileResourceDao.resourceListMap(categoryId, page, limit);

        Set<String> keys = listMap.keySet();

        // 设置文件下载地址
        keys.forEach(key -> {
            List<ResourceDto> resourceEntities = listMap.get(key);
            resourceEntities.forEach(resourceEntity -> {
                Long ossFileId = resourceEntity.getOssFileId();

                Optional.ofNullable(ossFileId).ifPresent((t) -> {
                    String downloadURL = ossService.getDownloadURL(ossFileId);
                    resourceEntity.setFileUrl(downloadURL);

                });

                Long thumbnailFileId = resourceEntity.getThumbnailFileId();

                if(ObjectUtil.isNotEmpty(thumbnailFileId)) {
                    String thumbnailFileUrl = ossService.getDownloadURL(thumbnailFileId);
                    resourceEntity.setThumbnailFileUrl(thumbnailFileUrl);
                } else {
                    resourceEntity.setThumbnailFileUrl(resourceEntity.getFileUrl());
                }


            });
        });
        return listMap;
    }


    /**
     * 上传图片资源文件
     * @param file
     * @param categoryName
     */
    @Transactional
    public void uploadResource(MultipartFile file, String categoryName) {
        // 判断分类是否存在
        CategoryEntity categoryEntity = mobileCategoryDao.getByName(categoryName);

        if(ObjectUtil.isNull(categoryEntity) || ObjectUtil.isNull(categoryEntity.getId())) {
            throw new RenException("当前分类:”" + categoryName + "“不存在");
        }
        // 获取最大排序
        Integer maxSort = mobileResourceDao.getMaxSort();

        // 正常不会为null, 若为null, 说明全部为null(后加字段)
        if(ObjectUtil.isNull(maxSort)) {
            List<ResourceEntity> resourceEntities = mobileResourceDao.selectList(null);

            AtomicReference<Integer> currentSort = new AtomicReference<>(1);

            resourceEntities.forEach(r -> {
                r.setSort(currentSort.getAndSet(currentSort.get() + 1));
            });

            updateBatchById(resourceEntities);

        }

        // 上传文件
        R upload = ossController.upload(file, "gs-cloud-disk", "wallper/" + DateTime.now().toDateStr());
        Long fileId = Convert.toLong(upload.getData());
        ResourceEntity entity = new ResourceEntity();

        OssEntity ossEntity = ossService.get(fileId);

        entity.setCategoryId(categoryEntity.getId());

        entity.setSort(maxSort);
        entity.setCategoryName(categoryEntity.getCategoryName());
        entity.setOldFileName(ossEntity.getOssFileName());
        entity.setOssFileId(ossEntity.getId());

        mobileResourceDao.insert(entity);
    }

}
